<?php
/**
 * 4s店逻辑层
 */
namespace AuctionBack\Logic;
use AuctionBack\Model\FourStoreModel;
use AuctionCore\Account\Back\Employee;
use AuctionCore\Other\Address;
class FourStoreLogic {

    Protected $autoCheckFields = false;
    
    /**
     * 4s店ID
     */
    private $fid;

    /**
     * 构造,初始化"4s店ID"
     */
    public function __construct($fid)
    {
        $this->fid = $fid;
        $this->model = D("FourStore","Model");
    }

    /**
     * 新增
     */
    public static function create($data)
    {   
        M()->startTrans();
        //添加渠道
        $come_from = [];
        $come_from['pid'] = 5;
        $come_from['from_name'] = $data['f_name'];
        $come_from['createtime'] = date("Y-m-d H:i:s", time());
        $channel_id = M('come_from')->add($come_from);

        $data['channel_id'] = $channel_id;
        $data['state'] = 1;
        $data['createtime'] = date("Y-m-d H:i:s", time());
        $fid = D("FourStore","Model") ->add($data);

        $bank_account = [];
        $bank_account['fid']  = $fid;
        $bank_account['bank_name'] = $data['bank_name'];
        $bank_account['card_no'] = $data['card_no'];
        $bank_account['account_name'] = $data['account_name'];
        $bank_account_id = M('fours_bank_account')->add($bank_account);
        //出错回滚
        if ($channel_id < 1 || $fid < 1 || $bank_account_id < 1) {

            M()->rollback();

            return false;
        }
        M()->commit();

        return $fid;
    }   

    /**
     * 修改
     */
    public static function update($data)
    {   
        M()->startTrans();
        //添加渠道
        $come_from = [];
        $channel = true;
        $come_from['from_name'] = $data['f_name'];
        $comeFrom = M('come_from')->where(['from_id'=>$data['channel_id']])->find();
        if ($comeFrom['from_name'] != $data['f_name']) {
            $channel = M('come_from')->where(['from_id'=>$data['channel_id']])->save($come_from);
        }
        $fourStore = [];
        $fourStore['f_name'] = $data['f_name'];
        $fourStore['addr'] = $data['addr'];
        $fourStore['contact'] = $data['contact'];
        $fourStore['phone'] =  $data['phone'];
        $fourStore['developer'] = $data['developer'];
        $fourStore['maintain_id'] = $data['maintain_id'];
        $fourStore['region_id'] = $data['region_id'];
        $fourStore['city'] = $data['city'];
        $fourStore['bank_name'] = $data['bank_name'];
        $fourStore['card_no'] = $data['card_no'];
        $fourStore['account_name'] = $data['account_name'];
        $fourStore['modifytime'] = date("Y-m-d H:i:s", time());
        $fs = D("FourStore","Model") ->where(['fid'=>$data['fid']])->save($fourStore);
        $bank_account = [];
        $bank_account['bank_name'] = $data['bank_name'];
        $bank_account['card_no'] = $data['card_no'];
        $bank_account['account_name'] = $data['account_name'];
        $bank_account['createtime'] = date("Y-m-d H:i:s", time());
        $bank_account = M('fours_bank_account')->where(['id'=>$data['account_id']])->save($bank_account);

        if ($data['account_id1'] > 0) {
            $bank_account1 = [];
            $bank_account1['bank_name'] = $data['bank_name1'];
            $bank_account1['card_no'] = $data['card_no1'];
            $bank_account1['account_name'] = $data['account_name1'];
            $bank_account1['createtime'] = date("Y-m-d H:i:s", time());
            $ba = M('fours_bank_account')->where(['id'=>$data['account_id1']])->save($bank_account1);
        }else{
            $bank_account1 = [];
            $bank_account1['fid'] = $data['fid'];
            $bank_account1['bank_name'] = $data['bank_name1'];
            $bank_account1['card_no'] = $data['card_no1'];
            $bank_account1['account_name'] = $data['account_name1'];
            $bank_account1['createtime'] = date("Y-m-d H:i:s", time());
            $ba = M('fours_bank_account')->add($bank_account1);
        }
        //出错回滚
        if ($channel < 1 || $fs < 1 || $bank_account < 1) {

            M()->rollback();

            return false;
        }
        M()->commit();

        return $fs;
    }   

    public function detail($fid)
    {   
        if($fid < 1) return false;
        return $this->model->where(['fid'=>$fid])->find();
    }

    /**
     * 4S店名称检查
     */
    public function checkFourStoreName($fourStoreName,$fid = 0)
    {   
        $map = [];
        if ($fid > 0) {
            $map['fid'] = ['neq',$fid];
        }
        $map['f_name'] = ['eq',$fourStoreName];
        return $fourStore = $this->model->where($map)->find();
    }

    /**
     * 列表
     */
    public static function getFourStoreList($page, $limit, $params)
    {
        $page = (int)$page < 1 ? 1 : (int)$page;
        $limit = (int)$limit < 1 ? 10 : (int)$limit;
        //搜索 
        $map = array();
        if ($params['bc_city']) {
            $map['city'] = array('in',$params['bc_city']);
        }
        if ($params['region_id']) {
            $map['region_id'] = array('eq',$params['region_id']);
        }
        if ($params['maintain_id']) {
            $map['maintain_id'] = array('eq',$params['maintain_id']);
        }
        if ($params['fid']) {
            $map['fid'] = array('eq',$params['fid']);
        }
        if ($params['f_name']) {
            $map['f_name'] = array('eq',$params['f_name']);
        }
        if ($params['developer_phone']) {
            $empIds = Employee::getEmpIdByMobile($params['developer_phone']);
            $map['developer'] = array('in',$empIds);
        }
        if ($params['maintain_phone']) {
            $mEmpIds = Employee::getEmpIdByMobile($params['maintain_phone']);
            $map['maintain_id'] = array('in',$mEmpIds);
        }
        $total = D('FourStore','Model')->where($map)->count();
        $list = D('FourStore','Model')->where($map)->limit($limit)->page($page)->order('fid desc')->select();
        $RegionLogic = D('Region','Logic');
        foreach ($list as $key => $value) {
            $developerInfo = Employee::user_info_id($value['developer']);
            $maintainInfo = Employee::user_info_id($value['maintain_id']);
            $list[$key]['developer_name'] = $developerInfo['real_name'];
            $list[$key]['developer_mobile'] = $developerInfo['mobile'];
            $list[$key]['maintain_name'] = $maintainInfo['real_name'];
            $list[$key]['maintain_mobile'] = $maintainInfo['mobile'];
            $RegionInfo = $RegionLogic->detail($value['region_id']);
            $list[$key]['region_name'] = $RegionInfo['region_name'];
            $list[$key]['isRelation'] = false;
            $foursAppraiser = self::getfoursAppraiser($value['fid']);
            if (!empty($foursAppraiser)) {
                $list[$key]['isRelation'] = true;
            }
        }
        $result = array(
            'list' => $list,
            'total' => $total
        );
        return $result;
    }
    /**
     * 4s账号信息
     */
    public function getFourStoreInfo($fid)
    {   
        if($fid < 1) return false;
        $map = [];
        $map['fid'] = ['eq',$fid];
        $fourStore = $this->model->where($map)->find();
        $accountInfo = M('fours_bank_account')->where($map)->select();
        $fourStore['accountInfo'] = $accountInfo;
        //城市名称
        $address = new Address();
        $fourStore['city_name'] = $address ->get_name_by_code($fourStore['city']);

        //找到开发人的分公司ID
        $fourStore['developer_bc_id'] = Employee::get_emp_branch_id($fourStore['developer']);
        $developerInfo = Employee::user_info_id($fourStore['developer']);
        $fourStore['developer_name'] = $developerInfo['real_name'];
        $fourStore['developer_mobile'] = $developerInfo['mobile'];
        //找到维护人的分公司ID
        $fourStore['maintain_bc_id'] = Employee::get_emp_branch_id($fourStore['maintain_id']);
        $maintainInfo = Employee::user_info_id($fourStore['maintain_id']);
        $fourStore['maintain_name'] = $maintainInfo['real_name'];
        $fourStore['maintain_mobile'] = $maintainInfo['mobile'];
        //找到片区
        $RegionInfo = D('Region','Logic')->detail($fourStore['region_id']);
        $fourStore['region_name'] = $RegionInfo['region_name'];
        return $fourStore;
    }

    /**
    * 启用
    */
    public function enable($fid,$channel_id)
    {   
        M()->startTrans();
        $ok = $this->model->where(array('fid'=>$fid))->save(array('state'=>'1'));
        if (!$ok) {
            M()->rollback();
            return false;
        }
        $ok1 = M('come_from')->where(['from_id'=>$channel_id])->save(['is_delete'=>0]);
        if (!$ok1) {
            M()->rollback();
            return false;
        }
        M()->commit();
        return true;
    }
    
    /**
    * 禁用
    */
    public function disable($fid,$channel_id)
    {   
        M()->startTrans();
        $ok = $this->model->where(array('fid'=>$fid))->save(array('state'=>'0'));
        if (!$ok) {
            M()->rollback();
            return false;
        }
        $ok1 = M('come_from')->where(['from_id'=>$channel_id])->save(['is_delete'=>1]);
        if (!$ok1) {
            M()->rollback();
            return false;
        }
        M()->commit();
        return true;
    }

    /**
    * 找到集团下4s店信息
    */
    public static function getFourStoreByBid($bid)
    {
        $fourStoreInfos = D("FourStore","Model")-> where(['b_id'=>$bid])->select();
        return $fourStoreInfos;
    }

    /**
    * 对应城市下不在当前片区下的4s店
    */
    public function getNotInFourStoreByCity($city,$rid)
    {
        if(empty($city)) return false;
        $map = [];
        $map['city'] = ['in',$city];
        $map['region_id'] = ['neq',$rid];
        $fourStoreInfos = D("FourStore","Model")->where($map)->select();
        return $fourStoreInfos;
    }

    /**
    * 找到当前片区下4s店
    */
    public function getInFourStoreByRid($rid)
    {
        if($rid < 0) return false;
        $fourStoreInfos = D("FourStore","Model")->where(['region_id'=>$rid])->select();
        return $fourStoreInfos;
    }

    /**
    * 找到当前集团下4s店城市
    */
    public function getInFourStoreByBid($bid)
    {
        if($bid < 0) return false;
        $fourStoreInfos = D("FourStore","Model")->where(['b_id'=>$bid])->select();
        return $fourStoreInfos;
    }


    /**
    * 解除片区关系
    */
    public function delRelationRegion($fids)
    {
        if(empty($fids)) return false;
        $map = [];
        $map['fid'] = ['in',$fids];
        $res = D("FourStore","Model")->where($map)->save(['region_id'=>0]);
        return $res;
    }
    /**
    * 绑定片区关系
    */
    public function addRelationRegion($fids,$rid)
    {
        if(empty($fids)) return false;
        $map = [];
        $map['fid'] = ['in',$fids];
        $res = D("FourStore","Model")->where($map)->save(['region_id'=>$rid]);
        return $res;
    }

    /**
    * 解除集团关系
    */
    public function delRelationBloc($fids)
    {
        if(empty($fids)) return false;
        $map = [];
        $map['fid'] = ['in',$fids];
        $res = D("FourStore","Model")->where($map)->save(['b_id'=>0]);
        return $res;
    }
    /**
    * 绑定集团关系
    */
    public function addRelationBloc($fids,$bid)
    {
        if(empty($fids)) return false;
        $map = [];
        $map['fid'] = ['in',$fids];
        $res = D("FourStore","Model")->where($map)->save(['b_id'=>$bid]);
        return $res;
    }



    /**
    *找到维护人关联4s店数量
    */
    public function getFourStoreCount($emp_id)
    {   
        $count = $this->model->where(['maintain_id'=>$emp_id])->count();
        return $count;
    }

    /**
    *找到维护人关联4s店
    */
    public function getFourStoreInfoByEmpId($emp_id)
    {   
        $FourStoreInfo = $this->model->field('fid,f_name')->where(['maintain_id'=>$emp_id])->select();
        return $FourStoreInfo;
    }

    /**
    *找到分公司下4s店(不在$bid集团下)
    **/
    public function getNotInBlocFourStore($branch_id,$bid)
    {
        $address = new Address();
        $citys = $address->getCityByBranchId($branch_id);
        $map = [];
        if (!empty($citys)) {
            $mapCitys = [];
            foreach ($citys as $key => $value) {
                $mapCitys[] = $value['city_code'];
            }
            $map['city'] = ['in',$mapCitys];
        }
        $map['b_id'] = ['neq',$bid];
        $res = $this->model->where($map)->select();
        return $res;
    }

    /**
    *找到当前4s店下评估师
    **/
    public function getfoursAppraiser($fid)
    {
        $prefix = C('DB_PREFIX');
        $map = [];
        $map['fa.f_id'] = $fid;
        $list = M('fours_appraiser')->alias("fa")->field("e.emp_id,e.real_name,e.username")
            ->join("{$prefix}employee e ON e.emp_id = fa.appraiser_id")
            ->where($map)->select();
        return $list;
    }

    /**
    *指定评估师下4s店数量
    **/
    public function getAppraiserFoursCount($emp_id)
    {
        return M('fours_appraiser')->where(['appraiser_id'=>$emp_id])->count();
    }

    /**
    *指定评估师下4s店信息
    **/
    public function getAppraiserFoursInfo($emp_id)
    {   
        $prefix = C('DB_PREFIX');
        $list = M('fours_appraiser')->alias("fa")->field("f.fid,f.f_name")
                ->join("{$prefix}fours f ON f.fid = fa.f_id")
                ->where(['fa.appraiser_id'=>$emp_id])->select();
        return $list;
    }


    /**
    *  4s店关联评估师提交
    */
    public function foursRelationAppraiserPost($fid,$postAppraiserIds)
    {
        $appraiser = M('fours_appraiser')->where(['f_id'=>$fid])->select();
        $appraiserIds = [];
        foreach ($appraiser as $key => $value) {
            $appraiserIds[] = $value['appraiser_id'];
        }
        if(empty($postAppraiserIds)){
            if (empty($appraiserIds)) return true; 
            foreach ($appraiserIds as $k => $val) {
                $res = $this->delRelationAppraiser($fid,$val);
                if (!$res) return false; 
            }
        }else{
            $add_spm = array_diff($postAppraiserIds, $appraiserIds);
            $del_spm = array_diff($appraiserIds, $postAppraiserIds);
            if (!empty($add_spm)) {
                foreach ($add_spm as $k1 => $v1) {
                    $res1 = $this->addRelationAppraiser(['f_id'=>$fid,'appraiser_id'=>$v1]);
                    if (!$res1) return false; 
                }
            }
            if (!empty($del_spm)) {
                foreach ($del_spm as $k2 => $v2) {
                    $res2 = $this->delRelationAppraiser($fid,$v2);
                    if (!$res2) return false; 
                } 
            }
        }
        return true;
    }

    /**
    * 解除片区与评估师关系
    */
    public function delRelationAppraiser($fid,$appraiserId)
    {
        if($appraiserId < 1) return false;
        if($fid < 1) return false;
        $map = [];
        $map['appraiser_id'] = ['eq',$appraiserId];
        $map['f_id'] = $fid;
        $res = M('fours_appraiser')->where($map)->delete();
        return $res;
    }
    /**
    * 绑定片区与维护人关系
    */
    public function addRelationAppraiser($data)
    {
        $data['createtime'] = date("Y-m-d H:i:s", time());
        $res = M('fours_appraiser')->add($data);
        return $res;
    }


    // public static function getTree($bc_list){
    //     if (!is_array($bc_list)) return false;
    //     $branchInfo = [];
    //     foreach ($bc_list as $key => $value) {
    //         $branchInfo[$value]['val'] = $key;
    //         $cityInfo = M('branch_city')->alias('bc')->field('aa.city_name,bc.city_code')
    //                     ->join(C('DB_PREFIX')."addr_area aa ON aa.city_code = bc.city_code")
    //                     ->where(['bc.branch_id'=>$key])->select();
    //         if ($cityInfo) {
    //             foreach ($cityInfo as $k => $val) {
    //                 $branchInfo[$value]['items'][$val['city_name']]['val'] = $val['city_code'];
    //                 $regionInfo = M('region')->field('region_name,rid')->where(['city'=>$val['city_code']])->select();
    //                 if ($regionInfo) {
    //                     foreach ($regionInfo as $k1 => $v1) {
    //                         $branchInfo[$value]['items'][$val['city_name']]['items'][$v1['region_name']]['val'] = $v1['rid'];
    //                         $maintain = M('region_maintain') ->alias('rm')->field('e.emp_id,e.real_name')
    //                                     ->join(C('DB_PREFIX')."employee e ON e.emp_id = rm.maintain_id")
    //                                     ->where(['rm.region_id'=>$v1['rid']])->select();
    //                         if ($maintain) {
    //                             foreach ($maintain as $k2 => $v2) {
    //                                 $branchInfo[$value]['items'][$val['city_name']]['items'][$v1['region_name']]['items'][$v2['real_name']] = $v2['emp_id'];
    //                             }
    //                         }
    //                     }
    //                 }
    //             }
    //         }
    //     }
    //     return $branchInfo;
    // }
}   




